package com.eboss.sbs.core;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.eboss.sbs.model.fuyou.FyMicropayRequest;
import com.eboss.sbs.model.fuyou.FyMicropayResponse;
import com.eboss.sbs.model.fuyou.FyQueryRequest;
import com.eboss.sbs.model.fuyou.FyQueryResponse;
import com.eboss.sbs.model.fuyou.FyRefundRequest;
import com.eboss.sbs.model.fuyou.FyRefundResponse;
import com.eboss.sbs.myapplication.MyApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.myokhttp.MyOkHttp;
import com.myokhttp.response.RawResponseHandler;
import com.mytools.tool.dialog.CustomTimingProgressDialog;
import com.mytools.tool.dialog.CustomTimingProgressDialog.DialogDismissEvent;
import com.mytools.tool.utils.MapUtil;
import com.mytools.tool.utils.StringUtil;

import java.lang.reflect.Type;
import java.util.Map;




public class FyBat {
	
    private static final String TAG = "FyBat";
//    public static String FUSM_URL = "http://121.40.224.25:9091/ZFTiming/api/fyTrade/pay";
//    public static String FUQUERY_URL = "http://121.40.224.25:9091/ZFTiming/api/fyTrade/query";
//    public static String FUREFUND_URL = "http://121.40.224.25:9091/ZFTiming/api/fyTrade/refund";
    
    public static String BASE_URL = "http://121.40.224.25:9091";
    public static String FUSM_URL = BASE_URL + "/ZFTiming/api/fyTrade/pay";
    public static String FUQUERY_URL = BASE_URL + "/ZFTiming/api/fyTrade/query";
    public static String FUREFUND_URL = BASE_URL + "/ZFTiming/api/fyTrade/refund";
    //富友 公私钥
    public static String FY_RSA_PRIVATE = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALi+gZ6+Y3UAao1IGkVPKVGeqdA+j0i4ebwJ4Fp+7Sn7Ys0TzO6X3maH01MzsgVVk/26QUf3QTvifXlZoDGp447oCB1SelZDRrVD69Bl/5unqH9BCbOweJqrWvb+OzzWRRpBHWhIqPPdbIFgm675BMR+7rxB+pvMxy6/GzopoYUvAgMBAAECgYB5MyowbbEsCijdJUdu3v85d8DqSJCR4cyja0tPs2N+Hlj0N6BDi0ixtTwTop+Q1lLvq2i2gOTAF9e/a+gnjNAnS2YuoUpGKgKgKxcWs/RZLrV98AShaMLuiHuUpVPovCMpY02OzY/bvlnDZng8/ON4xrygHtSq1Hc3FaLCqRcuMQJBAO2PD7xvecVNRLkMyRxfVlTwGDB7jrI2WpLqQ1Xh4orWpkzr+tu8Hod65eoiMdcslHw4QJJ3wadLX+Jg9jLQj9kCQQDHFd/Flk41lChu3f5hQH86KUi4GLg1Pl3SfWa66rSvTrhRJ/EZ+r2QvQDqKRY2o8NSXY7tQdu6vJ86yuxrsqBHAkBX/CGW6C7QraKjayHdeU4PXXGIG2sphEodmdhgqa3vQDsNyGT8F3uzMAiRpCKTkHZaX7dCyEoYPSmBPepRvb9ZAkA5HORaOblsE3nZ/GOKoMce91L+RVErLR4bUZBUFRsKo8mqtourSUxyplYJ1wmhWS+ihGaJV/hiRNRlOGvEpbTnAkAlwLoIdf3R4tH3uV2tE9l5WpJ75fxNd2Atl/ED1o78O3W6QOXJo/ulfByQmV3laUM5U+8OFynVwck2xEmt0Tzp";
    public static String FY_RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4voGevmN1AGqNSBpFTylRnqnQPo9IuHm8CeBafu0p+2LNE8zul95mh9NTM7IFVZP9ukFH90E74n15WaAxqeOO6AgdUnpWQ0a1Q+vQZf+bp6h/QQmzsHiaq1r2/js81kUaQR1oSKjz3WyBYJuu+QTEfu68QfqbzMcuvxs6KaGFLwIDAQAB";

    private Context mContext;
    private boolean isPaying = false; // 查询标识次数
    private String pay_type;
    private String client_sn00;		//本地创建的订单号
    private String order_no; 		//订单号
    private String merchantCd;		//富友商户号
    
    private String fy_terminal_id = "";		//设备终端号
    
    private CustomTimingProgressDialog Timedialog;
    
    private FYPayResultEvent payResultEvent;
    
    public FyBat(Context context, String merchantCd, FYPayResultEvent payResultEvent) {
    	this.payResultEvent = payResultEvent;
        this.mContext = context;
        this.merchantCd = merchantCd;
        
        fy_terminal_id = MyApplication.getmInstance().getLoginEntity().getActivateCode();
        
//        fy_terminal_id = SystemUtil.getImsi(mContext);
//        if(!StringUtil.isNull(fy_terminal_id)){
//        	int length = fy_terminal_id.length();
//        	if(length>=8){
//        		fy_terminal_id = fy_terminal_id.substring(length-8, length);
//        	}
//        }
        
//        imsi = SystemUtil.getImsi(mContext);
//        if(!StringUtil.isNull(imsi)){
//        	int length = imsi.length();
//        	if(length>=8){
//        		imsi = imsi.substring(length-8, length);
//        	}
//        }
        
    }

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isPaying) {
                query(client_sn00, pay_type, order_no);
            } else {
                Timedialog.dialogDismiss();
                toast("交易失败");
                handler.removeCallbacks(this);
            }
        }
    };

    /**
     * 富友扫码支付
     *
     * @param client_sn 本地创建的订单号（流水上传/本地记录用）
     * @param qrcode   （条码信息）
     * @param type     （支付方式：ALIPAY , WECHAT）
     * @param amount   （金额：分单位）
     */
    public void pay(final String client_sn, String qrcode, String type, int amount){//, final ActionCallbackListener<FyMicropayResponse> listener) {
    	
    	this.client_sn00 = client_sn;
    	
        FyMicropayRequest request = new FyMicropayRequest();
        request.setVersion("");//("1.0");		//版本号
        request.setIns_cd("08M0064989");		//机构号,接入机构在富友的唯一代码
        request.setMchnt_cd(merchantCd);		//商户号, 富友分配给二级商户的商户号
        request.setTerm_id(fy_terminal_id);				//终端号, 富友分配的终端设备号  设备后8位
        request.setRandom_str("");				//(StringUtils.createRandomStr(32));		//随机字符串
        request.setType(type);					//order_type订单类型:ALIPAY , WECHAT
        request.setGoods_des("消费");				//商品描述, 商品或支付单简要描述
        request.setGoods_detail("消费物品");		//商品详情, 商品名称明细
        request.setAddn_inf("");				//附加数据
        request.setMchnt_order_no("");			//(outTradeNo);	//商户订单号, 商户系统内部的订单号
        request.setCurr_type("CNY");			//货币类型,默认人民币：CNY
        request.setAmount(amount);				//order_amt	总金额, 订单总金额，单位为分
        request.setTerm_ip("");					//(NetUtils.getLocalIpAddress(mContext));	//终端IP
        request.setTxn_begin_ts("");			//(StringUtils.getFormatCurTime());			//交易起始时间, 订单生成时间，格式为yyyyMMddHHmmss
        request.setGoods_tag("");				//商品标记
        request.setAuth_code(qrcode);			//扫码支付授权码，设备读取用户的条码或者二维码 信息
        request.setSence("");//("1");			//支付场景,默认1；条码支付-1 声波支付-2
        request.setReserved_sub_appid("");		//子商户公众号id, 子商户配置多个公众号时必填
        request.setReserved_limit_pay("");		//限制支付,no_credit:不能使用信用卡

        pay_type = type;

        isPaying = true;
        // 除去sign组成map 按字典排序
        Map<String, String> tempMap = MapUtil.order(MapUtil.objectToMap(request, "sign", "reserved_sub_appid", "reserved_limit_pay"));
        MapUtil.removeNullValue(tempMap);
        
        Log.e("tempMap", tempMap.toString());
        Log.e("url", FUSM_URL);

        Timedialog = new CustomTimingProgressDialog(mContext, new DialogDismissEvent() {
			@Override
			public void dialogDismiss() {
				isPaying = false;
			}
		});
        Timedialog.show();
        Timedialog.setCancelable(false);

        MyOkHttp.get().post(mContext, FUSM_URL, tempMap, new RawResponseHandler() {

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Log.e(TAG, statusCode + "#" + error_msg);
                Timedialog.dialogDismiss();
                payResultEvent.onFailure(statusCode, error_msg, client_sn);
                toast(statusCode + ""+error_msg);
//                if (statusCode == 0) {
//                    Timedialog.dialogDismiss();
//                    ToastUtils.CustomShow(mContext, statusCode + ""+error_msg);
//                } else {
////                    handler.postDelayed(runnable, 5000);
//                }
            }

            @Override
            public void onSuccess(int statusCode, String response) {
                Log.e(TAG, statusCode + "#" + response);
                if (statusCode == 200 && !StringUtil.isNull(response)) {
                    FyMicropayResponse result = new Gson().fromJson(response, new TypeToken<FyMicropayResponse>() {}.getType());
                    if (result.getResult_code().equals("000000")) {
                        Timedialog.dialogDismiss();
                        toast("交易成功");
                        payResultEvent.onSuccess(result, client_sn);
                        order_no = result.getMchnt_order_no();
                    } else if (result.getResult_code().equals("030010")){ //用户使用支付密码
                        order_no = result.getMchnt_order_no();
                        handler.postDelayed(runnable, 5000);
                    } else {
                    	Timedialog.dialogDismiss();
                        Toast.makeText(mContext, result.getResult_code()+"#"+result.getResult_msg(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                	Timedialog.dialogDismiss();
                	Toast.makeText(mContext, statusCode+"#"+response, Toast.LENGTH_SHORT).show();
                }
            }
        });


    }


    /**
     * 订单查询（富友）
     *
     * @param type       （支付方式：ALIPAY , WECHAT）
     * @param outTradeNo （商户订单号）
     */
    public void query(final String client_sn, String type, String outTradeNo){//, final ActionCallbackListener<FyQueryResponse> listener) {
        FyQueryRequest request = new FyQueryRequest();
        request.setVersion("");//("1.0");			//版本号
        request.setIns_cd("08M0064989");			//机构号,接入机构在富友的唯一代码
        request.setMchnt_cd(merchantCd);		//富友分配的商户号
        request.setTerm_id(fy_terminal_id);					//终端号, 富友分配的终端设备号  设备后8位
        request.setOrder_type(type);				//订单类型:ALIPAY , WECHAT
        request.setMchnt_order_no(outTradeNo);		//商户系统内部的订单号
        request.setRandom_str("");//(StringUtils.createRandomStr(32));	//随机字符串，不长于32位

        // 除去sign组成map 按字典排序
        Map<String, String> tempMap = MapUtil.order(MapUtil.objectToMap(request, "sign", "reserved_sub_appid", "reserved_limit_pay"));
        MapUtil.removeNullValue(tempMap);
        Log.e("tempMap", tempMap.toString());

        Log.e("url", FUQUERY_URL);
        MyOkHttp.get().post(mContext, FUQUERY_URL, tempMap, new RawResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String response) {
                Log.e(TAG, statusCode + "#" + response);
                if (statusCode == 200 && !StringUtil.isNull(response)) {
                    FyQueryResponse result = new Gson().fromJson(response, new TypeToken<FyQueryResponse>() {}.getType());
                    if (result.getResult_code().equals("000000")) {
                        if (result.getTrans_stat().equals("SUCCESS")) {
                            Timedialog.dialogDismiss();
                            toast("交易成功");
                            payResultEvent.onSuccess(result, client_sn);
                        } else { //用户支付中。。
                            handler.postDelayed(runnable, 5000);
                        }
                    }else {
                    	Timedialog.dialogDismiss();
                        toast(result.getResult_code()+"#"+result.getResult_msg());
                    }
                } else {
                	Timedialog.dialogDismiss();
                    toast(statusCode+"#"+response);
                }
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
            	Timedialog.dialogDismiss();
            	payResultEvent.onFailure(statusCode, error_msg, client_sn);
            	toast(statusCode+"#"+error_msg);
            }
        });
    }


    public void refund(final String client_sn, String type, String outTradeNo, int amount){//, final ActionCallbackListener<FyRefundResponse> listener) {
        outTradeNo = order_no;
        FyRefundRequest request = new FyRefundRequest();
        request.setVersion("");//("1.0");			//版本号
        request.setIns_cd("08M0064989");			//机构号,接入机构在富友的唯一代码
        request.setMchnt_cd(merchantCd);		//富友分配的商户号
        request.setTerm_id(fy_terminal_id);					//终端号, 富友分配的终端设备号  设备后8位
        request.setMchnt_order_no(outTradeNo);		//商户系统内部的订单号
        request.setRandom_str("");					//(StringUtils.createRandomStr(32));	//随机字符串，不长于32位
        request.setOrder_type(type);				//订单类型:ALIPAY , WECHAT
        request.setRefund_order_no("");//(StringUtils.createOrderNo(null));	//商户退款单号
        request.setAmount(amount);					//总金额
        request.setRefund_amt(amount);				//退款金额
        request.setOperator_id("");					//操作员

        // 除去sign组成map 按字典排序
        Map<String, String> tempMap = MapUtil.order(MapUtil.objectToMap(request, "sign", "reserved_sub_appid", "reserved_limit_pay"));
        MapUtil.removeNullValue(tempMap);
        Log.e("tempMap", tempMap.toString());

        Log.e("url", FUREFUND_URL);

        MyOkHttp.get().post(mContext, FUREFUND_URL, tempMap, new RawResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String response) {
                Log.e(TAG, statusCode + "#" + response);
                if (statusCode == 200 && !StringUtil.isNull(response)) {
                    Type type = new TypeToken<FyRefundResponse>() {
                    }.getType();
                    Gson gson = new Gson();
                    FyRefundResponse result = gson.fromJson(response, type);
                    if (result.getResult_code().equals("000000")) {
                    	toast("退款成功");
                    	payResultEvent.onSuccess(result, client_sn);
                    } else {
                    	Timedialog.dialogDismiss();
                    	toast(result.getResult_code()+"#"+result.getResult_msg());
                    }
                } else {
                	Timedialog.dialogDismiss();
                	toast(statusCode+"#"+response);
                }
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
            	Timedialog.dialogDismiss();
            	payResultEvent.onFailure(statusCode, error_msg, client_sn);
            	toast(statusCode+"#"+error_msg);
            }
        });

    }
    
    private void toast(String msg){
    	Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }
    
	public interface FYPayResultEvent{
    	void onSuccess(FyMicropayResponse data, String client_sn);
    	void onSuccess(FyQueryResponse data, String client_sn);
    	void onSuccess(FyRefundResponse data, String client_sn);
    	void onFailure(int statusCode, String error_msg, String client_sn);
    }


}
